package com.example.waimai.contraller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.example.waimai.common.R;
import com.example.waimai.dto.DishDto;
import com.example.waimai.pojo.Category;
import com.example.waimai.pojo.Dish;
import com.example.waimai.pojo.DishFlavor;
import com.example.waimai.service.ServiceCategory;
import com.example.waimai.service.ServiceDish;
import com.example.waimai.service.ServiceDishFlavor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.*;

import java.util.Arrays;
import java.util.List;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

@RequestMapping("/dish")
@Slf4j
@RestController
public class DishContraller {

    @Autowired
    private ServiceDish serviceDish;
    @Autowired
    private ServiceDishFlavor serviceDishFlavor;
    @Autowired
    private ServiceCategory serviceCategory;
    @Autowired
    private RedisTemplate redisTemplate;
    @GetMapping("/page")
    public R<Page> pageR(int page,int pageSize,String name){
        Page<Dish> page1=new Page<>(page,pageSize);
        Page<DishDto> dishDtoPage=new Page<>(page,pageSize);
        LambdaQueryWrapper<Dish> lqw=new LambdaQueryWrapper<>();
        lqw.like(name!=null,Dish::getName,name);
        lqw.orderByAsc(Dish::getId);
        serviceDish.page(page1, lqw);

        //拷贝对象  为了使菜品分类显示出来
        BeanUtils.copyProperties(page1,dishDtoPage,"records");//忽略records,不拷贝此部分
        List<Dish> records = page1.getRecords();
        List<DishDto> list = records.stream().map((item) -> {
            DishDto dishDto = new DishDto();
            BeanUtils.copyProperties(item,dishDto);
            Long categoryId = item.getCategoryId();//分类id
            //根据id查询分类对象
            Category category =serviceCategory.getById(categoryId);//ServiceCategory.getById(categoryId);
            if(category != null){
                String categoryName = category.getName();
                dishDto.setCategoryName(categoryName);
            }
            return dishDto;
        }).collect(Collectors.toList());
        dishDtoPage.setRecords(list);
        return R.success(dishDtoPage);
    }

    @PostMapping
    public R<String> save(@RequestBody DishDto dishDto){
        log.info("新增菜品：{}",dishDto.toString());
        serviceDish.saveWithFlavor(dishDto);
        return null;
    }

    //updata
    @GetMapping("/{id}")
    public  R<DishDto> updatedish(@PathVariable Long id){
        log.info("修改菜品:{}",id);
        DishDto dishDto = serviceDish.updatadishWithFlavor(id);
        return R.success(dishDto);
    }
    //updata save

    @PutMapping
    public R<String> UpdataWithSave(@RequestBody DishDto dishDto){
        log.info(dishDto.toString());
        serviceDish.updatasaveWithFlaver(dishDto);

        //清除redis中所有菜品数据
        //Set keys = redisTemplate.keys("dish_*");
        //redisTemplate.delete(keys);

        //指定删除
        String keys="dish_"+dishDto.getCategoryId()+"_1";
        redisTemplate.delete(keys);
        return R.success("修改成功");
    }

    @GetMapping("/list")
    public R<List<DishDto>> list(Dish dish){
        String key="dish_"+dish.getCategoryId()+"_"+dish.getStatus();
        List<DishDto> list1=null;
        //从redis中获取缓存数据
         list1= (List<DishDto>) redisTemplate.opsForValue().get(key);
         if(list1!=null){
             return R.success(list1);
         }

        LambdaQueryWrapper<Dish> lwq=new LambdaQueryWrapper<>();
        lwq.eq(dish.getCategoryId()!=null,Dish::getCategoryId,dish.getCategoryId());
        lwq.eq(Dish::getStatus,1);
        lwq.orderByAsc(Dish::getSort).orderByDesc(Dish::getUpdateTime);

        List<Dish> list = serviceDish.list(lwq);
            list1 = list.stream().map((item) -> {
            DishDto dishDto = new DishDto();
            BeanUtils.copyProperties(item,dishDto);
            Long categoryId = item.getCategoryId();//分类id
            //根据id查询分类对象
            Category category =serviceCategory.getById(categoryId);//ServiceCategory.getById(categoryId);
            if(category != null){
                String categoryName = category.getName();
                dishDto.setCategoryName(categoryName);
            }
            Long dishId=item.getId();
            LambdaQueryWrapper<DishFlavor> lqw=new LambdaQueryWrapper<>();
            lqw.eq(DishFlavor::getDishId,dishId);
            List<DishFlavor> list2 = serviceDishFlavor.list(lqw);
            dishDto.setFlavors(list2);
            return dishDto;
        }).collect(Collectors.toList());
        //如果不存在，将数据库的数据缓存到redis
        redisTemplate.opsForValue().set(key,list1,60, TimeUnit.MINUTES);
        return R.success(list1);
    }

    @PostMapping("status/{id}")//设置菜品状态
    public R<String> status(@PathVariable int id){
        return  null;
    }


   @DeleteMapping("/{ids}")
    public  R<String> delete(@PathVariable Long ids){
       List<String> List = Arrays.asList(String.valueOf(ids));
       List<Long> idsList = List.stream().map(s -> Long.parseLong(s.trim())).collect(Collectors.toList());

       serviceDish.DeleteWithdish(idsList);
        return R.success("菜品删除成功");
    }
}
